<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>    
</head>
<body>
    <div id="app">  
      <div>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete"  >批量删除</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="openDlg"  >添加</el-button>
      </div>      
      <el-table
        :data="books"
        border
        style="width: 1100px"
        ref="myTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column 
          type="selection"  
          align="center" 
          width="50">          
        </el-table-column>
        <el-table-column
          prop="f_image"
          label="图片"
          width="180"
          v-if="colVisible"
          align="center">
        </el-table-column>
        <el-table-column
          prop="f_id"
          label="书号"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="f_title"
          label="书名"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="f_author"
          label="作者"
          align="center">
        </el-table-column>
        <el-table-column
          prop="f_type"
          label="类型"
          align="center">
        </el-table-column>
        <el-table-column
          prop="f_price"
          label="价格"
          :formatter="moneyFormat"
          align="center">
        </el-table-column>
        <el-table-column label="操作"  align="center" width="200">
          <template slot-scope="scope">            
            <el-button
              size="mini"
              type="success"
              icon="el-icon-edit"
              @click="openDlg2(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div>
        <el-tag type="success">总价格：￥{{totalPrice}}</el-tag>
      </div>

      <div>
        <el-dialog
          title="添加"
          :visible.sync="dlgVisible"
          width="50%"
          >
          <el-form ref="book" :model="book" label-width="80px">
            <el-form-item label="书名">
            <el-input v-model="book.f_title"></el-input>
            </el-form-item>
            <el-form-item label="作者">
                <el-input v-model="book.f_author"></el-input>
            </el-form-item>
            <el-form-item label="价格">
                <el-input v-model="book.f_price"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="book.f_type" placeholder="请选择图书类型">
                <el-option label="小说" value="小说"></el-option>
                <el-option label="教材" value="教材"></el-option>
                <el-option label="散文" value="散文"></el-option>
                <el-option label="诗歌" value="诗歌"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="封面">              
                <input type="file"  @change="onChange"><p></p>
                <img :src="filePath" alt="" style="width:150px;height:150px">
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onAdd">添加</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>              
        </el-dialog>
      </div>

      <div>
        <!-- :before-close="handleClose" -->
        <el-dialog
          title="编辑"
          :visible.sync="dlgVisible2"
          
          width="50%"
          >
          <el-form ref="book2" :model="book2" label-width="80px">
            <el-form-item label="书名">
            <el-input v-model="book2.f_title"></el-input>
            </el-form-item>
            <el-form-item label="作者">
                <el-input v-model="book2.f_author"></el-input>
            </el-form-item>
            <el-form-item label="价格">
                <el-input v-model="book2.f_price"></el-input>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="book2.f_type" placeholder="请选择图书类型">
                <el-option label="小说" value="小说"></el-option>
                <el-option label="教材" value="教材"></el-option>
                <el-option label="散文" value="散文"></el-option>
                <el-option label="诗歌" value="诗歌"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="封面">              
                <input type="file"  @change="onChange2"><p></p>
                <img :src="filePath" alt="" style="width:150px;height:150px">
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onUpdate">修改</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>              
        </el-dialog>
      </div>

    </div> 
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
    
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script> 

    <script>
        let vm = new Vue({
            el:'#app',
            data:{   
                    colVisible:true,                 
                    books:[], //数据库的图书,
                    selectBooks:[], //待删除的图书
                    dlgVisible:false, //添加对话框可见性
                    dlgVisible2:false, //编辑对话框可见性
                    path:'http://localhost:44355/Content/img/', 
                    book:{f_id:0, f_title:'', f_author:'', f_price:0, f_image:'' },
                    book2:{f_id:0, f_title:'', f_author:'', f_price:0, f_image:'' },
                    filePath:'',
                    img:null, //保存上传的图片信息
            },

            //计算属性
            computed: {
              totalPrice(){
                  let sum = 0;
                  this.books.forEach(bk=>sum += bk.f_price)
                  return sum;
              },
            },

            /**********方法**********/
            methods:{
                bindTable(){
                    let _this = this //保存对Vue实例的引用
                    //发出ajax请求，获取服务器中图书表的记录
                    axios.get('http://localhost:44355/Book/Index')
                         .then(function (rs) {
                        _this.books = rs.data //将获取的图书保存到数组
                    })
                },
                
                //货币格式化
                moneyFormat(row, column, cellValue, index){
                    return '￥' + cellValue
                },

                //当选择发生变化时
                handleSelectionChange(val){
                  this.selectBooks = val                  
                },

                
                //上传图片到Server
                onChange(e){
                    this.img = e.target.files[0] //将表单中所选择的图片保存到Vue对象中

                    let _this = this                    
                    let formData = new FormData()
                    //formData与MVC中Book控制器的 public JsonResult upload( HttpPostedFileBase image )的image参数相匹配
                    formData.append('image',this.img) 
                    
                    //图片预览
                    _this.filePath = window.URL.createObjectURL(this.img);
                    

                    axios.post('http://localhost:44355/Book/upload',formData)
                         .then(function (rs) {        
                            _this.book.f_image = rs.data.image //将保存到服务器中的新文件名返回到                                               
                            console.log("上传图片Ok："+_this.book.f_image  );
                           
                    })
                },

                //上传图片到Server2
                onChange2(e){
                    this.img = e.target.files[0] //将表单中所选择的图片保存到Vue对象中

                    let _this = this                    
                    let formData = new FormData()
                    //formData与MVC中Book控制器的 public JsonResult upload( HttpPostedFileBase image )的image参数相匹配
                    formData.append('image',this.img) 
                    
                    //图片预览
                    _this.filePath = window.URL.createObjectURL(this.img);
                    
                    

                    axios.post('http://localhost:44355/Book/upload',formData)
                         .then(function (rs) {        
                            _this.book2.f_image = rs.data.image //将保存到服务器中的新文件名返回到                                               
                            console.log("上传图片Ok："+_this.book2.f_image  );
                           
                    })
                },



                //添加图书
                onAdd(){                  
                    let _this = this
                    axios.post('http://localhost:44355/Book/add',_this.book)
                         .then(function (rs) {
                            _this.book.f_id = 0
                            _this.book.f_title = '' 
                            _this.book.f_author = ''
                            _this.book.f_price = 0
                            _this.book.f_type = ''
                            _this.book.f_image = ''
                           
                            //关闭对话框
                            _this.dlgVisible = false

                            _this.bindTable() //刷新图书列表
                    })
                },

                //打开编辑对话框
                openDlg2(i,row){
                  this.dlgVisible2 = true
                  this.book2.f_id = row.f_id
                  this.book2.f_title = row.f_title
                  this.book2.f_author = row.f_author
                  this.book2.f_price = row.f_price
                  this.book2.f_type = row.f_type
                  this.book2.f_image = row.f_image

                  //预览图片
                  this.filePath  = this.path + row.f_image  // http://localhost:8888/Content/pic/XX.jpg
                  

                  
                  console.log('编辑book2.f_image：'+this.book2.f_image);
                },

                //修改图书
                onUpdate(){                  
                    let _this = this
                    
                    console.log(this.book2);
                    axios.post('http://localhost:44355/Book/update',_this.book2)
                         .then(function (rs) {
                            console.log(rs.data);

                            _this.book2.f_id = 0
                            _this.book2.f_title = '' 
                            _this.book2.f_author = ''
                            _this.book2.f_price = 0
                            _this.book2.f_type = ''
                            _this.book2.f_image = ''

                            //关闭对话框
                            _this.dlgVisible2 = false

                            //console.log('编辑图片路径：'+this.filePath);

                            _this.bindTable() //刷新图书列表
                    })
                },

                //删除
                handleDelete(index, row){
                  this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {                          
                        //删除
                        let _this = this //保存对Vue实例的引用
                        
                        axios.get('http://localhost:44355/Book/delete/' + row.f_id)
                            .then(function (rs) {  
                                                    
                                //删除后，刷新表格，显示最新的数据
                                axios.get('http://localhost:44355/Book/Index')
                                .then(function (rs) {
                                _this.books = rs.data //将获取的图书保存到数组
                                })
                            })
                        
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                  }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除'});          
                  });
                },

                //批量删除
                handleBatchDelete(){
                  this.$confirm('确定要删除吗？, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    //ajax删除
                    let _this = this
                    let ids = ''
                    _this.selectBooks.forEach(bk=>{
                      ids += bk.f_id + ','  //1,2,3
                    })
                    //割尾巴
                    ids = ids.substring(0,ids.length-1)
                    axios.get('http://localhost:44355/Book/batchDelete/' + ids)
                         .then(function (rs) {
                          //发出ajax请求，获取服务器中图书表的记录
                            axios.get('http://localhost:44355/Book/Index')
                                .then(function (rs) {
                                _this.books = rs.data //将获取的图书保存到数组
                          })
                        console.log(rs.data);
                    })


                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    });
                  }).catch(() => {
                    this.$message({
                      type: 'info',
                      message: '已取消删除'
                    });          
                  });
                },
            
                //打开添加对话框
                openDlg(){
                  this.filePath = ''
                  this.dlgVisible = true;
                },
                
                

                handleClose(done) {                  
                  this.$confirm('确认关闭？')
                    .then(_ => {
                      done();
                    })
                    .catch(_ => {});
                },
              },

            //生命周期：类似webform的 XX_load( )
            created(){
                this.bindTable()
            },
        })
    </script>
</body>
</html>